package com.innjia.sys.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.innjia.sys.entity.UserEntity;
import com.innjia.sys.service.OAuth2LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝OAuth2 实现
 * <br>
 * 2017-11-19
 *
 * @author zhouxianglh@gmail.com
 */
@Service("oAuth2LoginServiceAliPay")
public class OAuth2LoingServiceAliPayImpl implements OAuth2LoginService {
    private static final Logger LOGGER = LoggerFactory.getLogger(OAuth2LoingServiceAliPayImpl.class);

    @Value("${login.aliPay.appId}")
    private String appId;

    @Value("${login.aliPay.host}")
    private String host;

    @Value("${login.aliPay.RSA2.private}")
    private String appPrivateKey;

    @Value("${login.aliPay.RSA2.aliPay}")
    private String aliPayPublicKey;

    /**
     * authcode 访问 https://openauth.alipaydev.com/oauth2/publicAppAuthorize.htm?app_id=2016080700190106&scope=auth_base&redirect_uri=http://www.innjia.com
     * 获得,注意这里的 scope ,auth_base 时在这里就可以获得uid,但是获取token不可以用来查询用户基本信息;如果是 auth_user 则这里不会返回uid,需要调查询用户信息接口查询
     * <br/>
     * 这里同产品确认过,不需要用户信息,所以auth_base更合适一些
     * <br/>
     * 参考:https://docs.open.alipay.com/284/106001
     *
     * @param requestParams
     * @return
     */
    @Override
    public Map<String, String> getAccessToken(Map<String, String> requestParams) {
        AlipayClient alipayClient = new DefaultAlipayClient(host, appId, appPrivateKey, "json", "UTF-8", aliPayPublicKey, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(requestParams.get(OAuth2LoginService.KEY_AUTH_CODE));
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
            LOGGER.error(response.getBody());
            Map<String, String> result = new HashMap<>(2);
            result.put(OAuth2LoginService.KEN_TOKEN, response.getAccessToken());
            result.put(OAuth2LoginService.KEN_UID, response.getAlipayUserId());
            return result;
        } catch (AlipayApiException e) {
            LOGGER.error("", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public UserEntity getUserInfo(Map<String, String> requestParams) {
        AlipayClient alipayClient = new DefaultAlipayClient(host, appId, appPrivateKey, "json", "UTF-8", aliPayPublicKey, "RSA2");
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        try {
            AlipayUserInfoShareResponse response = alipayClient.execute(request, requestParams.get(OAuth2LoginService.KEN_TOKEN));
            LOGGER.error(response.getBody());
            UserEntity user = new UserEntity();
            user.setAlipayId(response.getUserId());
            user.setUserName(response.getNickName());
            return user;
        } catch (Exception e) {
            LOGGER.error("", e);
            throw new RuntimeException(e);
        }
    }
}
